import React, { useState } from 'react'
import { useDropzone } from 'react-dropzone'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { Upload, FileText, File, CheckCircle, XCircle } from 'lucide-react'
import { motion, AnimatePresence } from 'framer-motion'
import toast from 'react-hot-toast'
import { uploadApi } from '../services/api'

const FileUpload = () => {
  const [uploadProgress, setUploadProgress] = useState({})
  const queryClient = useQueryClient()

  // Excel 上传
  const uploadExcelMutation = useMutation({
    mutationFn: uploadApi.uploadExcel,
    onSuccess: (response) => {
      toast.success(`Excel文件处理成功，生成了 ${response.data.generated_files_count} 个任务`)
      queryClient.invalidateQueries(['tasks'])
    },
    onError: (error) => {
      toast.error(`Excel上传失败: ${error.response?.data?.detail || error.message}`)
    }
  })

  // Word 上传
  const uploadWordMutation = useMutation({
    mutationFn: uploadApi.uploadWord,
    onSuccess: (response) => {
      toast.success('Word文件处理成功')
      console.log('Word processing result:', response.data)
    },
    onError: (error) => {
      toast.error(`Word上传失败: ${error.response?.data?.detail || error.message}`)
    }
  })

  const onDrop = async (acceptedFiles) => {
    for (const file of acceptedFiles) {
      const fileId = Date.now() + Math.random()
      
      setUploadProgress(prev => ({
        ...prev,
        [fileId]: { name: file.name, status: 'uploading', progress: 0 }
      }))

      try {
        if (file.name.endsWith('.xlsx')) {
          await uploadExcelMutation.mutateAsync(file)
        } else if (file.name.endsWith('.docx')) {
          await uploadWordMutation.mutateAsync(file)
        } else {
          throw new Error('不支持的文件格式')
        }

        setUploadProgress(prev => ({
          ...prev,
          [fileId]: { ...prev[fileId], status: 'success', progress: 100 }
        }))

        // 3秒后移除成功状态
        setTimeout(() => {
          setUploadProgress(prev => {
            const { [fileId]: removed, ...rest } = prev
            return rest
          })
        }, 3000)

      } catch (error) {
        setUploadProgress(prev => ({
          ...prev,
          [fileId]: { ...prev[fileId], status: 'error', error: error.message }
        }))
      }
    }
  }

  const { getRootProps, getInputProps, isDragActive } = useDropzone({
    onDrop,
    accept: {
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': ['.xlsx'],
      'application/vnd.openxmlformats-officedocument.wordprocessingml.document': ['.docx']
    },
    multiple: true,
    maxSize: 10 * 1024 * 1024 // 10MB
  })

  return (
    <div className="h-full p-6">
      <div className="max-w-4xl mx-auto">
        <div className="mb-6">
          <h2 className="text-xl font-semibold text-gray-900">文件上传</h2>
          <p className="text-sm text-gray-500 mt-1">
            上传Excel或Word文件，AI将自动生成测试任务
          </p>
        </div>

        {/* 上传区域 */}
        <div
          {...getRootProps()}
          className={`
            border-2 border-dashed rounded-lg p-8 text-center cursor-pointer transition-all
            ${isDragActive 
              ? 'border-blue-400 bg-blue-50' 
              : 'border-gray-300 hover:border-blue-400 hover:bg-gray-50'
            }
          `}
        >
          <input {...getInputProps()} />
          
          <div className="flex flex-col items-center">
            <Upload className={`w-12 h-12 mb-4 ${isDragActive ? 'text-blue-500' : 'text-gray-400'}`} />
            
            {isDragActive ? (
              <div>
                <p className="text-lg font-medium text-blue-700 mb-2">
                  释放文件以开始上传
                </p>
                <p className="text-sm text-blue-600">
                  AI将自动处理您的文件
                </p>
              </div>
            ) : (
              <div>
                <p className="text-lg font-medium text-gray-700 mb-2">
                  拖拽文件到此处，或点击选择文件
                </p>
                <p className="text-sm text-gray-500 mb-4">
                  支持 Excel (.xlsx) 和 Word (.docx) 文件，最大 10MB
                </p>
                
                <div className="flex items-center justify-center space-x-6 text-xs text-gray-400">
                  <div className="flex items-center">
                    <FileText className="w-4 h-4 mr-1" />
                    Excel → 测试任务
                  </div>
                  <div className="flex items-center">
                    <File className="w-4 h-4 mr-1" />
                    Word → 测试用例
                  </div>
                </div>
              </div>
            )}
          </div>
        </div>

        {/* 上传进度 */}
        <AnimatePresence>
          {Object.entries(uploadProgress).map(([fileId, progress]) => (
            <motion.div
              key={fileId}
              initial={{ opacity: 0, y: 10 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0, y: -10 }}
              className="mt-4 p-4 bg-white border border-gray-200 rounded-lg"
            >
              <div className="flex items-center justify-between">
                <div className="flex items-center space-x-3">
                  <div className="flex-shrink-0">
                    {progress.status === 'uploading' && (
                      <div className="w-6 h-6 border-2 border-blue-600 border-t-transparent rounded-full animate-spin" />
                    )}
                    {progress.status === 'success' && (
                      <CheckCircle className="w-6 h-6 text-green-500" />
                    )}
                    {progress.status === 'error' && (
                      <XCircle className="w-6 h-6 text-red-500" />
                    )}
                  </div>
                  
                  <div className="flex-1 min-w-0">
                    <p className="text-sm font-medium text-gray-900 truncate">
                      {progress.name}
                    </p>
                    <p className="text-xs text-gray-500">
                      {progress.status === 'uploading' && 'AI正在处理文件...'}
                      {progress.status === 'success' && '处理完成'}
                      {progress.status === 'error' && `处理失败: ${progress.error}`}
                    </p>
                  </div>
                </div>

                <div className="text-right">
                  <div className={`
                    text-xs px-2 py-1 rounded-full
                    ${progress.status === 'uploading' ? 'bg-blue-100 text-blue-800' :
                      progress.status === 'success' ? 'bg-green-100 text-green-800' :
                      'bg-red-100 text-red-800'
                    }
                  `}>
                    {progress.status === 'uploading' && '处理中'}
                    {progress.status === 'success' && '成功'}
                    {progress.status === 'error' && '失败'}
                  </div>
                </div>
              </div>

              {progress.status === 'uploading' && (
                <div className="mt-3">
                  <div className="w-full bg-gray-200 rounded-full h-2">
                    <div 
                      className="bg-blue-600 h-2 rounded-full transition-all duration-300"
                      style={{ width: '60%' }} // 模拟进度
                    />
                  </div>
                </div>
              )}
            </motion.div>
          ))}
        </AnimatePresence>

        {/* 使用说明 */}
        <div className="mt-8 grid grid-cols-1 md:grid-cols-2 gap-6">
          <div className="card">
            <div className="card-header">
              <h3 className="text-lg font-medium flex items-center">
                <FileText className="w-5 h-5 mr-2 text-green-600" />
                Excel 文件处理
              </h3>
            </div>
            <div className="card-content">
              <p className="text-sm text-gray-600 mb-3">
                上传包含测试用例的Excel文件，AI将自动解析并生成对应的测试任务。
              </p>
              <div className="text-xs text-gray-500 space-y-1">
                <div>• 支持多个测试用例</div>
                <div>• 自动解析步骤和验证点</div>
                <div>• 生成标准YAML格式任务文件</div>
              </div>
            </div>
          </div>

          <div className="card">
            <div className="card-header">
              <h3 className="text-lg font-medium flex items-center">
                <File className="w-5 h-5 mr-2 text-blue-600" />
                Word 文档处理
              </h3>
            </div>
            <div className="card-content">
              <p className="text-sm text-gray-600 mb-3">
                上传需求文档，AI将分析功能需求并自动生成对应的测试用例。
              </p>
              <div className="text-xs text-gray-500 space-y-1">
                <div>• 智能需求分析</div>
                <div>• 自动生成测试场景</div>
                <div>• 包含正向和异常流程</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}

export default FileUpload